package com.neusoft.demo.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.neusoft.demo.po.User;
import com.neusoft.demo.service.UserService;

@Controller
public class LoginController {
	
	@Autowired
	private UserService userService;

	@RequestMapping("/login")
	public String login() {
		
		return "login";
	}
	
	@RequestMapping("/checkLogin")
	public String checkLogin(User user,String code,Model model,HttpSession session) {
		if(!code.equalsIgnoreCase(session.getAttribute("code").toString())) {
			model.addAttribute("err","验证码不正确");
			return "login";
		}else {
			User loginUser = userService.findByUser(user);
			if(loginUser!=null) {
				session.setAttribute("user", loginUser);
				System.out.println(loginUser);
				return "index";
			}else {
				model.addAttribute("err", "用户名或密码错误");
				return "login";
			}
		}
	}
	
	@RequestMapping("/register")
	public String register() {
			return "register";
	}
	@RequestMapping("/registerUser")
	public String registerUser(User user,String code,Model model,HttpSession session) {
		if(!code.equalsIgnoreCase(session.getAttribute("code").toString())) {
			model.addAttribute("err","验证码不正确");
			return "register";
		}else {
			userService.regiseter(user);
			return "login";
		}
		
	}
	@RequestMapping("cancelLogin")
	public String cancelLogin(HttpSession session) {
		session.removeAttribute("user");
		return "login";
	}

	//个人中心
		@RequestMapping("selfInfo")
		public String selfInfo(HttpSession session,Model model) {
			User user = (User) session.getAttribute("user");
			if (user != null) {
				model.addAttribute("user", user);
				return "self_info";
			}else {
				return "login";
			}
			
		}
		
		@RequestMapping("updateUser")
		public String updateUser(User user,HttpSession session,Model model) {
			userService.updateUser(user);
			User user1 = userService.findById(user.getUid());
			model.addAttribute("user", user1);
			return "self_info";
		}

}
